package com.example.lib5.hashTab;

public class HashTabDemo {
    public static void main(String[] args) {
        HashTab hashTab = new HashTab(11);
        //添加
        hashTab.add(new Emp(24, "唐三"));
        hashTab.add(new Emp(13, "小舞"));
        hashTab.add(new Emp(31, "千仞雪"));
        hashTab.add(new Emp(6, "地方"));
        hashTab.add(new Emp(15, "随时"));
        hashTab.add(new Emp(18, "嗯嗯"));
        hashTab.add(new Emp(8, "特"));
        //遍历
        hashTab.list();
        System.out.println("查找…………………………………………");
        Emp empById = hashTab.findEmpById(8
        );
        System.out.println(empById);
    }
}
class HashTab {
    private EmpLinkedList[] empLinkedLists;
    int size;
    public HashTab(int size) {
        empLinkedLists = new EmpLinkedList[size];
        for (int i = 0; i < empLinkedLists.length; i++) {
            empLinkedLists[i] = new EmpLinkedList();
        }
        this.size = size;
    }
    public void add(Emp emp) {
        //获取那个数组位置
        int index = hashFun(emp.id);
        //添加到对应位置的
        empLinkedLists[index].add(emp);
    }
    public void list() {
        for (int i = 0; i < empLinkedLists.length; i++) {
            empLinkedLists[i].list(i);
        }
    }
    public int hashFun(int id) {
        return id % size;
    }
    public Emp findEmpById(int id) {
        return empLinkedLists[hashFun(id)].findEmpById(id);
    }
}
class EmpLinkedList {
    private Emp head;
    public void add(Emp emp) {
        if (head == null) {
            head = emp;
            return;
        }
        Emp temp = head;
        while (true) {
            if (temp.next == null) {
                break;
            }
            temp = temp.next;
        }
        temp.next = emp;
    }
    public void list(int i) {
        if (head == null) {
            System.out.println("第" + (i+1) + "链表为空");
            return;
        }
        Emp temp = head;
        while (true) {
            System.out.println("第" + i + "链表" + temp.toString());
            if (temp.next == null) {
                break;
            }
            temp = temp.next;
        }
    }
    public Emp findEmpById(int id) {
        //判断链表是否为空，为空退出
        if (head==null) {
            System.out.println("链表为空");
            return null;
        }
        //死循环链表，找到节点；找到最后一个还是没有，就设置为
        Emp temp=head;
        while (true) {
            if (temp.id==id) {
                break;
            }
            if (temp.next==null) {
                temp=null;
                break;
            }
            temp=temp.next;
        }
        return temp;
    }
}
//表示一个聘员
class Emp {
    public int id;
    public String name;
    public Emp next;//next默认为null
    @Override
    public String toString() {
        return "Emp{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
    public Emp(int id, String name) {
        this.id = id;
        this.name = name;
    }
}